let { HttpRequest, globalData, CloudFunction, UserAccess, addUserStat, mfutil, URLChangeCommon } = getApp();
let provice = require('./../../provice.json');
let city = require('./../../city.json');
const app = getApp();
Component({
  mixins: [],
  data: {
    num: 0,   //兴趣个数
    maxnum: 0,   //最大选择个数,
    apiType: null,
    type: null,
    textIndex: 0,
    successActive: false,   //提交弹窗状态
    selectList: [],   //问卷问题
    cityOptions: [],
    selectedList: [],  //选择的item
    titleValue: '',
    provinceValue: '',
    cityValue: '',
    userProvinceCode: '',
    userCityCode: '',
    illegal: false,
    router: '/pages/integral-question',
    pagetitle: '问卷',
    pickerActive: false, //省市筛选弹窗
    city: '',
    userProvince: '',  //提交的省份
    userCity: '',      //提交的城市
    value: [0, 0, 0],
    sucvalue: [0, 0],
    provice: [],
    city: [],
    showCity: [{ "name": "北京市", "code": 110100 }],   //默认
    mobile_txet: []
  },
  props: {
    id: {},
    json: {}
  },
  async onLoad() {
    if (this.props.json.tile_info.question.type == 'input') {
      this.setData({
        province: provice.province,
        city: city.city,
        showCity: city.city[0],
      })
    }

    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileEnd'+'进入结束页'
   
    }
    console.log(this.props.json.tile_info.points, 'TileEnd');
    let tracks = addUserStat(customAccessoptions)


  },
  didMount() {


    console.log(this.props);
    this.setData({
      mobile_txet: this.props.json.tile_info.mobile_complete_text_rich
    })

    let maxnum = '';
    let { selectList } = this.data;
    let selectedList = selectList.find((value) => {
      return value.selected == true
    })

    this.props.json.tile_info.question.type == 'radio' ? maxnum = 1 : maxnum = this.props.json.tile_info.question.max_options
    this.setData({
      type: this.props.json.tile_info.options[0].type,
      textType: this.props.json.tile_info.question.type,
      apiType: this.props.json.tile_info.type,
      id: this.props.id,
      maxnum: maxnum,
      selectList: this.props.json.tile_info.options,
      selectedList,
      tileId: this.props.json.tile_info.id,
      heightScreen: globalData.screenHeight,
      // 省市

    })
    if (this.props.json.tile_info.question.type == 'input') {
      this.setData({
        province: provice.province,
        city: city.city,
        showCity: city.city[0],
      })
    }
  },
  didUpdate() { },
  didUnmount() { },
  methods: {
    onQuestionNavChange() {
      let { selectList } = this.data;
      selectList.forEach(value => {
        delete value.selected
      });
      this.setData({
        num: 0,   //兴趣个数
        maxnum: 0,   //最大选择个数,
        selectedList: null,
        selectList
      })
      this.props.onQuestionNavChange();
    },
    // 文字多选择
    itemSelect(event) {
      let { selectList, selectedList, maxnum, num } = this.data;
      let { id, selected } = event.currentTarget.dataset;
      let selectItem = '';
      if (num >= maxnum && !selected) {
        my.alert({
          content: `您最多能选择${maxnum}个选项!`
        })
      }
      if (num <= maxnum && selected) {   //当前状态为选中
        let i = ''
        selectList.forEach((value, index) => {
          if (value.option_number == id) {
            console.log('取消')
            value.selected = false;
            // i = selectedList.findIndex((v) => {
            //   return value.option_number == id
            // })
            // console.log(i, '0000000000000000000')
          }
        })
        // selectedList.splice(i, 1);
        // console.log(selectedList,'删除selectedList')
        num -= 1
      } else if (num < maxnum && !selected) {
        // console.log('添加', this.data.selectedList,this.data.selectList)
        selectList.forEach((value) => {
          if (value.option_number == id) {
            value.selected = true;
            // selectedList.push(value)
            console.log(value, 'value')
          }
        })
        // console.log(selectList, '添加selectedList')
        num += 1
      }
      this.setData({
        selectList,
        // selectedList,
        num
      })
    },
    /**
     * 文字单选
     * @param {*} event 
     */
    onChange1(event) {
      let { selectList } = this.data;
      let textIndex = event.detail.value[0];
      selectList.forEach((value, index) => {
        if (textIndex == index) {
          value.selected = true;
        } else {
          delete value.selected;
        }
      })
      this.setData({
        selectList,
        // selectedList: item,
        textIndex
      })
    },
    // 省市筛选
    onChange(e) {
      let value = !this.data.city[e.detail.value[0]][e.detail.value[1]] ? [e.detail.value[0], 0] : e.detail.value;
      this.setData({
        value,
        showCity: this.data.city[value[0]],
      });
    },
    /**
   * 省市遮罩点击
   */
    cityChange() {
      my.hideKeyboard();
      let { pickerActive, value } = this.data;

      this.setData({
        pickerActive: !pickerActive,   //弹窗改变
        value
      })

    },
    // 取消省市筛选弹窗
    exitChangeSuc() {
      let { pickerActive } = this.data;
      this.setData({
        pickerActive: !pickerActive,   //弹窗改变   
      })
    },
    // 提交省市筛选
    cityChangeSuc() {
      let { pickerActive, userProvince, userCity, value, city, province, area } = this.data;
      this.setData({
        cityValue: ''
      })

      globalData.userInfo.province = province[value[0]].name;
      globalData.userInfo.city = city[value[0]][value[1]].name;
      // globalData.userInfo.area = area[this.data.city[value[0]][value[1]].code][value[2]].item_name;
      globalData.userInfo.userProvinceCode = province[value[0]].code;
      globalData.userInfo.userCityCode = city[value[0]][value[1]].code;
      // globalData.userInfo.userAreaCode = area[this.data.city[value[0]][value[1]].code][value[2]].item_code;
      let item = 'formData.city'
      this.setData({
        pickerActive: !Boolean(pickerActive),   //弹窗改变
        [item]: province[value[0]].name == city[value[0]][value[1]].name ? city[value[0]][value[1]].name : province[value[0]].name + city[value[0]][value[1]].name,
        userProvince: province[value[0]].name,
        userCity: city[value[0]][value[1]].name,
        userProvinceCode: province[value[0]].code,
        userCityCode: city[value[0]][value[1]].code,
        // saveActive: true,
        sucvalue: value
      })

      var provinceValue = this.data.userProvince;
      var cityValue = this.data.userCity;

      if (provinceValue == cityValue) {

        // debugger
        this.setData({
          cityOptions: [{
            type: "text", value: this.data.userProvinceCode,
            desc: provinceValue,

          },
          {
            type: "text", value: this.data.userCityCode,
            desc: cityValue,
          }],
          provinceValue
        })

      } else {
        console.log(provinceValue, cityValue);
        this.setData({
          cityOptions: [{
            type: "text", value: this.data.userProvinceCode,
            desc: provinceValue,

          },
          {
            type: "text", value: this.data.userCityCode,
            desc: cityValue,
          }],
          provinceValue, cityValue
        })

      }
      // console.log(this.data.userProvinceCode, this.data.userCityCode);



      console.log(this.data.cityOptions);


      // this.saveActiveFn(true)

    },
    /**
     * input输入
     * @param {*} event 
     */
    inputChange(event) {
      let { json } = this.props;
      let { value } = event.detail;
      let setValue = value;
      let type = json.tile_info.question.sub_type;

      // if (type == 'string') {
      //   let reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/
      //   if (reg.test(value)) {
      //     setValue = value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/g, '')
      //   }
      // }
      if (type == 'number') {
        let reg = /^[0-9]*$/;
        if (!reg.test(value)) {
          setValue = value.replace(/[^\d]/g, '');
        }
      }
      // if (type == 'date') {
      //   let reg = /^[0-9]*$/;
      //   if (!reg.test(value)) {
      //     setValue = value.replace(/[^\d]/g, '');
      //   }
      // }
      // if (type == 'provincecity') {
      //   console.log('省市筛选');
      // }
      this.setData({
        titleValue: null
      })
      this.setData({
        titleValue: setValue
      })
    },
    BlurChange(event) {

      let { value } = event.detail;
      this.setData({
        titleValue: value
      })
    },
    dataSelect() {
      let time = new Date();
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      my.datePicker({
        format: 'yyyy-MM-dd',
        currentDate: '2000-01-01',
        startDate: '1960-01-01',
        endDate: `${y}-${m}-${d}`,
        success: (res) => {
          let titleValue = res.date.replace(/-/g, '/')
          this.setData({
            titleValue
          })
        },
      });
    },
    // 省市筛选
    citySelect() {
      this.cityChange();
    },
    /**
 * 
 * @param {*} event 图片问卷1item点击选择
 */
    selectItem(event) {
      let { item, selected } = event.currentTarget.dataset;
      let { selectList, num, maxnum, selectedList } = this.data;
      if (num >= maxnum && Boolean(selected) == false) {
        my.alert({
          content: `您最多能选择${maxnum}个选项!`
        })
        return
      }
      selectList.forEach((val) => {
        val.selected == 'undefined' ? val.selected = false : '';
        if (val.option_number == item) {
          if (Boolean(val.selected) == false) {
            val.selected = true
            num += 1
          } else if (Boolean(val.selected) == true) {
            delete val.selected
            num -= 1
          }
        }
      });
      this.setData({
        selectList,
        num
      });
    },
    //文字单选提交
    async TextRadioSub() {

      let { json } = this.props;
      let { selectedList, apiType, id, maxnum, textIndex, selectList, tileId } = this.data;
      console.log(textIndex, 'textIndextextIndextextIndextextIndextextIndex')
      // if (json.tile_info.question.required && textIndex === null) {
      //   my.showToast({
      //     content: `请选择1个选项`,
      //     type: 'fail',
      //     duration: 1500,
      //   })
      //   return
      // }
      selectList.forEach((value, index) => {
        if (index == textIndex) {
          value.selected = true
        } else {
          delete value.selected
        }
      })
      // let question = json.tile_info.question; 
      let selectListed = null
      // if (json.tile_info.question.otype == 'input') {
      //   selectListed = selectList.find((value) => {
      //     return value.selected == true;
      //   })
      // }
      // let template = await CloudFunction('get', {});
      // if (id == template.data[1].id) {
      //   selectList = [
      //     {
      //       "type": "text",
      //       "value": selectListed.value,
      //       "desc": ""
      //     }
      //   ]
      // } else if (id == template.data[2].id) {
      //   selectList = [
      //     {
      //       "type": "text",
      //       "value": selectListed.value,
      //       "desc": ""
      //     }
      //   ]
      // }
      let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/")
      // json.tile_info.question.type = json.tile_info.question.otype;
      // delete json.tile_info.question.otype;
      let question = {
        max_options: json.tile_info.question.max_options,
        required: json.tile_info.question.required,
        text: json.tile_info.question.text,
        type: json.tile_info.question.otype ? json.tile_info.question.otype : json.tile_info.question.type
      }
      let bodyObj = {
        member_id_type: 1,
        do_datetime: time,
        question,
        options: selectList
      }
      let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${apiType}/${id}/done?member_id=${globalData.userInfo.memberId}`;
      my.showLoading({
        content: '提交中···'
      });
      console.log(selectList, 'selectListselectListselectListselectListselectList', json.tile_info.question)
      let res = await HttpRequest(path, 'POST', '', bodyObj);
      my.hideLoading({
        page: this
      });
      if (res.data.code == 0) {
        this.setData({
          successActive: true,
          selectedList: [],
          selectList: []
        })
      } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
        my.alert({
          content: res.data.msg
        })
      } else {
        mfutil.launchErrPage(53001)
      }
      /**
         * 用户行为记录埋点
         */
      let routerArr = getCurrentPages();
      let options = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.props.json.tile_info.id,
        String4: ''
      }
      let track = UserAccess(options)

      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileDone_'+this.props.json.tile_info.id+'_文字单选提交TileDone',
        // tileId: this.props.json.tile_info.id,
        // points: this.props.json.tile_info.points
      }
      let tracks = addUserStat(customAccessoptions)
      console.log(id, 'TileDone');
      // console.log(options,'optionsoptionsoptionsoptions')
    },
    //**文字多选提交 */
    async submitText() {

      // console.log(options,'optionsoptionsoptionsoptions')
      let { json } = this.props;
      console.log(json, '-------------------------')
      let { selectList, apiType, id, maxnum } = this.data;
      let selectedNum = selectList.find(value => {
        return value.selected == true
      })
      console.log(selectList, 'selectedListselectedListselectedList')
      if (json.tile_info.question.required && !selectedNum) {
        my.showToast({
          content: `请至少选择1个选项`,
          type: 'fail',
          duration: 1500,
        })
        return
      } else {
        this.setData({
          questionActive: false
        })
        let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/");
        let bodyObj = {
          member_id_type: 1,
          do_datetime: time,
          question: json.tile_info.question,
          options: selectList
        }
        let bodyIn = {
          do_datetime: time
        }
        console.log(bodyObj, 'bodyObjbodyObjbodyObjbodyObj')
        let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${apiType}/${id}/done?member_id=${globalData.userInfo.memberId}`;
        my.showLoading({
          content: '提交中···'
        });
        let res = await HttpRequest(path, 'POST', '', bodyObj);
        my.hideLoading({
          page: this
        });
        if (res.data.code == 0) {
          this.setData({
            successActive: true,
            num: 0,   //兴趣个数
            maxnum: 0,   //最大选择个数,
            apiType: null,
            type: null,
            // selectedList: []
          })

        } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
          my.alert({
            content: res.data.msg
          })
        } else {
          mfutil.launchErrPage(53001)
        }

      }
      /**
      * 用户行为记录埋点
      */
      let routerArr = getCurrentPages();
      let options = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.props.json.tile_info.id,
        String4: ''
      }
      let track = UserAccess(options)


      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileDone_'+this.props.json.tile_info.id+'_文字多选提交TileDone',
        // tileId: this.props.json.tile_info.id,
        // points: this.props.json.tile_info.points
      }
      let tracks = addUserStat(customAccessoptions)
      console.log(id, 'TileDone');
    },
    /**图片提交 */
    async submitImg() {
      // console.log(options,'optionsoptionsoptionsoptions')
      let { selectList, apiType, id, maxnum } = this.data;
      let { json } = this.props;
      let selectedNum = selectList.find(value => {
        return value.selected == true
      })
      if (json.tile_info.question.required && !selectedNum) {
        if (maxnum > 1) {
          my.showToast({
            content: `请至少选择1个选项`,
            type: 'fail',
            duration: 1500,
          })
        } else {
          my.showToast({
            content: `请选择1个选项`,
            type: 'fail',
            duration: 1500,
          })
        }

        return
      } else {
        let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/");
        let bodyObj = {
          member_id_type: 1,
          do_datetime: time,
          question: json.tile_info.question,
          options: selectList
        }
        console.log(globalData.userInfo.memberId);

        let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${apiType}/${id}/done?member_id=${globalData.userInfo.memberId}`;
        if (json.tile_info.done == 0) {
        }
        my.showLoading({
          content: '提交中···'
        });
        let res = await HttpRequest(path, 'POST', '', bodyObj);
        my.hideLoading({
          page: this
        });
        if (res.data.code == 0) {
          this.setData({
            successActive: true,
            num: 0,   //兴趣个数
            maxnum: 0,   //最大选择个数,
            apiType: null,
            type: null,
            selectedList: []
          })

        } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
          my.alert({
            content: res.data.msg
          })
        } else {
          mfutil.launchErrPage(53001)
        }

      }
      /**
       * 用户行为记录埋点
       */
      let routerArr = getCurrentPages();
      let options = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.props.json.tile_info.id,
        String4: ''
      }
      let track = UserAccess(options)

      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileDone_'+this.props.json.tile_info.id+'_图片提交TileDone',
        // tileId: this.props.json.tile_info.id,
        // points: this.props.json.tile_info.points
      }
      let tracks = addUserStat(customAccessoptions)
      console.log(id, 'TileDone');

    },
    /** input提交 */
    async submitInput() {

      let { selectList, cityOptions, titleValue, cityValue, provinceValue, apiType, id } = this.data;
      let { json } = this.props;
      console.log(json.tile_info.question.required, titleValue);

      if (json.tile_info.question.sub_type != 'provincecity' && json.tile_info.question.required && titleValue === '') {
        my.alert({
          content: '请输入回答内容'
        })
        return
      }
      if (json.tile_info.question.sub_type == 'provincecity' && provinceValue === '' && cityValue === '') {
        my.alert({
          content: '请输入回答内容'
        })
        return
      }
      let { illegal } = this.data;
      // if (titleValue != '') {
      //   console.log(titleValue , '11111111@@@');
      //   await my.tb.textRiskIdentification({
      //     data: {
      //       text: titleValue
      //     },
      //     success: (textRiskres) => {
      //       textRiskres.data.result.checkPoints.forEach((value, index) => {
      //         if (value.label != 'normal') {
      //           my.alert({
      //             content: '填写内容不合规，请进行修改'
      //           })
      //           this.setData({
      //             illegal: true
      //           })
      //         }
      //       })
      //     },
      //     fail: () => {
      //       my.alert({ title: '检查失败' });
      //       console.log('fail', '@000000000000');
      //     },
      //   })
      //   if (this.data.illegal) {
      //     this.setData({
      //       illegal: false
      //     })
      //     return
      //   }
      // }

      selectList[0].value = titleValue;
      let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/");
      let bodyObj = {
        member_id_type: 1,
        do_datetime: time,
        question: json.tile_info.question,
        options: selectList[0].value ? selectList : cityOptions
      }
      console.log(bodyObj , '@9999999999999999');
      // if (json.related.todo >= 1 || json.tile_info.limit == 0 || json.tile_info.limit > 0) {
      let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${apiType}/${id}/done?member_id=${globalData.userInfo.memberId}`;
      my.showLoading({
        content: '提交中···'
      });
      let res = await HttpRequest(path, 'POST', '', bodyObj);
      my.hideLoading({
        page: this
      });
      console.log(res.data, '111111111111@@@@@@@@@@@@@');

      if (res.data.code == 0) {
        this.setData({
          successActive: true,
          apiType: null,
          type: null,
        })

      } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
        my.alert({
          content: res.data.msg
        })
      } else {
        mfutil.launchErrPage(53001)
      }
      // } 

      /**
     * 用户行为记录埋点
     */
      let routerArr = getCurrentPages();
      let options = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.props.json.tile_info.id,
        String4: ''
      }
      let track = UserAccess(options);

      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileDone_'+this.props.json.tile_info.id+'_input提交TileDone',
        // tileId: this.props.json.tile_info.id,
        // points: this.props.json.tile_info.points
      }
      let tracks = addUserStat(customAccessoptions)
      console.log(id, 'TileDone');
    },
    shareFn() {
      my.showSharePanel();
    },
    urlChange(event) {

      console.log(event);

      let { item } = event.currentTarget.dataset;
      URLChangeCommon(item)
      /**
  * 用户行为记录埋点
  */
      let routerArr = getCurrentPages();
      let params = app.globalData.params;
      let channel = app.globalData.channel;
      let UserAccessoptions = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.props.json.tile_info.id,
        String4: item.cta_button_name

      }
      let track = UserAccess(UserAccessoptions)

      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileCTA_'+this.props.json.tile_info.id+'_'+item.cta_button_name
       
      }

      let tracks = addUserStat(customAccessoptions)
    },
  },
});
